package org.myspringframework.mvc.render;

import org.myspringframework.mvc.RequestProcessorChain;
import org.myspringframework.mvc.type.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * org.myspringframework.mvc.render <br>
 * 页面渲染器
 * @author jaymin
 * @since 2021/5/22
 */
public class ViewResultRender implements ResultRender{
    public static final String VIEW_PATH = "/templates/";
    /**
     * 视图
     */
    private ModelAndView modelAndView;

    /**
     * 1. 如果入参类型是ModelAndView,则直接赋值给成员变量.<br>
     * 2. 如果入参类型是String,则为视图，需要包装之后才赋值给成员变量<br>
     * 3.  针对其他情况，则直接抛出异常 <br>
     * @param result
     */
    public ViewResultRender(Object result) {
        if(result instanceof ModelAndView){
            this.modelAndView = (ModelAndView) result;
        }else if(result instanceof String){
            this.modelAndView = new ModelAndView().setView((String)result);
        }else {
            throw new RuntimeException("illegal request result type");
        }
    }

    @Override
    public void render(RequestProcessorChain requestProcessorChain) throws Exception {
        HttpServletRequest httpServletRequest = requestProcessorChain.getHttpServletRequest();
        HttpServletResponse httpServletResponse = requestProcessorChain.getHttpServletResponse();
        String path = modelAndView.getView();
        Map<String, Object> model = modelAndView.getModel();
        for (Map.Entry<String, Object> entry : model.entrySet()) {
            httpServletRequest.setAttribute(entry.getKey(),entry.getValue());
        }
        // 重定向,JSP
        httpServletRequest.getRequestDispatcher(VIEW_PATH +path).forward(httpServletRequest, httpServletResponse);

    }
}
